package com.beiding.fastmock.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 丁常磊
 * @date 2021/7/20 17:51
 */

public class ScriptUtils {

    /**
     * 转换后的对象中只接受三种数据类型
     * Map List Serializable
     * 如果非以上类型则为null
     *
     * @param obj
     * @return
     */
    public static Object convert(Object obj) {

        if (obj instanceof ScriptObjectMirror) {
            ScriptObjectMirror sj = (ScriptObjectMirror) obj;
            if (sj.isArray()) {
                List list = new ArrayList();
                for (int i = 0; i < sj.size(); i++) {
                    Object o = sj.get(i + "");
                    list.set(i, convert(o));
                }
                return list;
            } else {
                if (sj.isFunction()) {
                    return null;
                }
                JSONObject map = new JSONObject();
                for (Map.Entry<String, Object> entry : sj.entrySet()) {
                    map.put(entry.getKey(), convert(entry.getValue()));
                }
                return map;
            }
        }

        if (obj instanceof Map) {
            Map<String, Object> z = (Map) obj;
            if (!(z instanceof JSONObject)) {
                Map map = new HashMap();
                for (Map.Entry<String, Object> entry : z.entrySet()) {
                    map.put(entry.getKey(), convert(entry.getValue()));
                }
                return map;
            }
            for (Map.Entry<String, Object> entry : z.entrySet()) {
                entry.setValue(convert(entry.getValue()));
            }
            return obj;
        }

        if (obj instanceof List) {
            List z = (List) obj;
            if (!(z instanceof JSONArray)) {
                List list = new JSONArray();
                for (Object o : z) {
                    list.add(convert(o));
                }
                return list;
            }
            for (int i = 0; i < z.size(); i++) {
                z.set(i, convert(z.get(i)));
            }
            return z;
        }
        if (obj instanceof Serializable) {
            return obj;
        }
        return null;
    }

}
